<?php
namespace app\api\controller;

use app\common\model\Storelabel;
use app\common\model\Storelabelconnect;
use app\common\model\Userinstore;
use app\common\model\Userfocus;
use app\admin\model\Advertise;
use app\admin\model\Advertiselocal;
use app\admin\model\Advertiselocalconnect;
use app\admin\model\Advertisestoreconnect;
use app\admin\model\Advertiseticketconnect;
use app\admin\model\Store;
use app\admin\model\Ticket;


class Home extends Base
{

    /**
     * 首页数据
     */
    public function getHomeFrame()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        // 公告
        $announcement = $this->getAnnouncement();

        // 分类
        $typeList = $this->getTypeList();

        // 广告位
        //$advertiselocal = $this->getAdvertiselocal();
        // 广告
        $advertises = $this->getAdvertise();

        // 最新商品
        $storegoods = $this->getStoregoods();

        // 店铺(人气排名)
        $storeByComeIn = $this->getStores(['status'=>1], 'countInStore DESC', 20);

        // 店铺(最新发布排名)
        $storeByCreateAt = $this->getStores(['status'=>1], 'createDate DESC', 20);

        // 我关注的店铺
        $myFocusStore = $this->getMyFocusStore($param->userId);

        $data = [
            'announcement' => $announcement ? : '',
            'typeList' => $typeList ? : '',
            //'advertiselocal' => $advertiselocal ? : '',
            'advertises' => $advertises ? : '',
            'storegoods' => $storegoods ? : '',
            'storeByComeIn' => $storeByComeIn ? : '',
            'storeByCreateAt' => $storeByCreateAt ? : '',
            'myFocusStore' => $myFocusStore ? : '',
        ];

        return show(config('status.success_code'), self::MSG_SUCCESS, $data);
    }

    /**
     * 获取公告
     */
    public function getAnnouncement()
    {
        $where = [];
        $model = new \app\admin\model\Announcement();
        $field = 'id, title, createTime';
        $result = $model->where($where)->field($field)->limit(0, 4)->order('createTime DESC')->select();
        if (!$result) {
            return [];
        }

        return $result;
    }

    /**
     * 获取分类
     */
    public function getTypeList()
    {
        $where = [];
        $model = new \app\admin\model\Type();
        $field = 'id, typeName, imgUrl';
        $result = $model->where($where)->field($field)->limit(0, 100)->order('createTime DESC')->select();
        if (!$result) {
            return [];
        }

        return $result;
    }

    /**
     * 获取广告位
     */
    public function getAdvertiselocal()
    {
        $where = [];
        $model = new Advertiselocal();
        $field = 'id, advertiseLocalNumb, advertiseLocalName, topimgurl, type';
        $result = $model->where($where)->field($field)->limit(0, 4)->order('advertiseLocalNumb ASC')->select();
        if (!$result) {
            return [];
        }

        return $result;
    }

    /**
     * 获取广告
     */
    public function getAdvertise(){
        $where = [
            'status' => 1
        ];
        $Advertiselocal = Advertiselocal::where($where)->order('advertiseLocalNumb ASC')->select();
        if(!empty($Advertiselocal)){
            $data['sowingad'] = [];
            $data['windowad'] = [];
            foreach ($Advertiselocal as &$v){
                if($v['type'] == 0){
                    array_push($data['sowingad'],$v);
                }elseif ($v['type'] == 1){
                    array_push($data['windowad'],$v);
                }else{
                    //
                }
            }
            // 首页轮播图广告
            $this->getLaunchAd($data['sowingad']);

            // 首页橱窗广告
            $this->getLaunchAd($data['windowad']);

            return $data;
        }else{
            return [];
        }
    }

    private function getLaunchAd($adtype){
        $nowdate = date('Y-m-d H:i:s',time());
        if(!empty($adtype)){
            foreach ($adtype as &$v){
                $Advertiselocalconnect = Advertiselocalconnect::where('advertiseLocalId',$v['id'])->select();
                if($Advertiselocalconnect){
                    //有该广告位的广告
                    //再判断该广告位里面的广告是否有正在投放中的
                    $ad = [];
                    foreach ($Advertiselocalconnect as $value){
                        $Advertise = Advertise::where('id',$value['advertiseId'])->find();
                        if($nowdate>=$Advertise['startTime'] && $nowdate<$Advertise['endTime']){
                            if($Advertise->advertiseUrlStatus == 0){
                                $store = Advertisestoreconnect::where('advertiseId',$Advertise['id'])->find();
                                $Advertise['storeId'] = $store->storeId;
                            }elseif ($Advertise->advertiseUrlStatus == 1){
                                $ticket = Advertiseticketconnect::where('advertiseId',$Advertise['id'])->find();
                                $Advertise['ticketId'] = $ticket->ticketId;
                            }
                            $ad['id'] = $Advertise['id'];
                            $ad['advertiseImgUrl'] = $Advertise['advertiseImgUrl'];
                            $ad['advertiseTitle'] = $Advertise['advertiseTitle'];
                            $ad['advertiseUrlStatus'] = $Advertise['advertiseUrlStatus'];
                            if(isset($Advertise['storeId'])){
                                $ad['storeId'] = $Advertise['storeId'];
                            }
                            if(isset($Advertise['ticketId'])){
                                $ad['ticketId'] = $Advertise['ticketId'];
                            }
                        }
                    }
                    if(!empty($ad)){
                        //有正在投放中的广告
                        $v['ad'] = $ad;
                    }
                }else{
                    //该广告位没有广告显示广告位的默认内容
                }
            }
        }
    }

    /**
     * 获取商品
     */
    public function getStoregoods()
    {
        $where = [];
        $model = new \app\common\model\Storegoods();
        $field = 'id, storeId, title, imgUrl, createDate';
        $result = $model->where($where)->field($field)->limit(0, 20)->order('createDate DESC')->select();
        if (!$result) {
            return [];
        }

        return $result;
    }

    /**
     * 获取店铺
     */
    public function getStores($where, $order, $limit = 20)
    {
        $model = new Store();
        $field = 'id, name, imgUrl, phone, countInStore';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order($order)->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            // 店铺标签
            $storeLabelIds = Storelabelconnect::where('storeId', $item['id'])->field('storeLabelId')->select();
            $storeLabelIds = array_column($storeLabelIds, 'storeLabelId');
            $storelabels = Storelabel::whereIn('id', $storeLabelIds)->field('storeLabel')->select();
            $item['storelabels'] = $storelabels;

            // 店铺券
            $ticket = self::getTicket($item['id']);
            if($ticket){
                $item['ticketId'] = $ticket['id'];
                $item['ticketName'] = $ticket['name'];
            }
        }

        return $result;
    }

    /**
     * 获取我关注的店铺
     */
    public function getMyFocusStore($userId)
    {
        $where = [
            'a.userId' => $userId,
        ];
        $model = db('userfocus');
        $field = 's.id, s.name, s.imgUrl, s.phone, s.countInStore';
        $result = $model->alias('a')->where($where)->join('store s', 'a.storeId = s.id')->field($field)->limit(0, 20)->order('a.focusTime DESC')->select();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item) {
            // 店铺标签
            $storeLabelIds = Storelabelconnect::where('storeId', $item['id'])->field('storeLabelId')->select();
            $storeLabelIds = array_column($storeLabelIds, 'storeLabelId');
            $storelabels = Storelabel::whereIn('id', $storeLabelIds)->field('storeLabel')->select();
            $item['storelabels'] = $storelabels;

            // 店铺券
            $ticket = self::getTicket($item['id']);
            if($ticket){
                $item['ticketId'] = $ticket['id'];
                $item['ticketName'] = $ticket['name'];
            }
        }

        return $result;
    }

    /*public function abcd(){
        $Ticket = \app\common\model\Ticket::where(true)->select();
        $Specialofferruleconnect = Specialofferrule::where(true)->select();
        foreach ($Ticket as $v){
            foreach ($Specialofferruleconnect as $v1){
                if($v['specialOfferId'] == $v1['id']){
                    \app\admin\model\Ticket::where('id',$v['id'])->update(['name'=>$v1['specialOfferName']]);
                }
            }
        }
    }*/

    /*public function abcde(){
        $Ticket = \app\admin\model\Ticket::where('status',['=',5],['=',4],'OR')->select();
        $Specialofferruleconnect = Specialofferruleconnect::where(true)->select();
        foreach ($Ticket as $v){
            foreach ($Specialofferruleconnect as $v1){
                if($v['id'] == $v1['ticketId']){
                    \app\admin\model\Ticket::where('id',$v['id'])->update(['storeId'=>$v1['storeId']]);
                }
            }
        }
    }*/

    public static function getinstoreAndcountFocus($storeId){
        $Userinstore = Userinstore::where('storeId',$storeId)->select();
        $countInStore = 0;
        $countFocus = 0;
        $Userfocus = Userfocus::where('storeId',$storeId)->select();
        if($Userfocus){
            $countFocus = count($Userfocus);
        }
        if($Userinstore){
            foreach ($Userinstore as $item){
                $countInStore += (int)$item['inStoreCount'];
            }
        }
        $data['countInStore'] = $countInStore;
        $data['countFocus'] = $countFocus;

        return $data;
    }

    public static function getTicket($storeId){
        $Ticket = Ticket::where(['storeId'=>$storeId,'status'=>5])->find();

        return $Ticket;
    }
}